package com.liusp.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.liusp.dao.ReportDao;
import com.liusp.pojo.Member;
import com.liusp.pojo.ReportData;
import com.liusp.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = ReportService.class)
@Transactional
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportDao reportDao;

    @Override
    public Map<String,Object> getMemberReport() {
        //查询月份
        List<String> date = reportDao.getMonth();
        Map<String,Object> result = new HashMap<>();
        Set<String> month = getMonth(date);
        result.put("month",month);

        //获取每月会员数
        List<Integer> memberCount = getIntegers(month);
        result.put("memberCount", memberCount);

        return result;
    }

    @Override
    public Map<String, Object> getSetmealReport() {
        return Collections.emptyMap();
    }

    @Override
    public ReportData getBusinessReportData() {
        ReportData reportData = new ReportData();
        reportData.setReportDate(String.valueOf(new Date())); //今天日期
        return null;
    }

    /**
     * 获取每月会员数
     * @param month 月份集合
     * @return 每月总数
     */
    private List<Integer> getIntegers(Set<String> month) {
        // 查询每个对应月份的会员总数
        List<Integer> memberCount = new ArrayList<>();
        for (String monthStr : month) {
            // 从 "03月" 提取数字 3
            int m = Integer.parseInt(monthStr.replace("月", ""));
            int count = reportDao.getMemberCountByMonth(m);
            memberCount.add(count);
        }
        return memberCount;
    }

    /**
     * 查询月份
     * @param date 日期集合
     * @return 不重复月份集合
     */
    private Set<String> getMonth(List<String> date){
        Set<String> month = new TreeSet<>((m1, m2) -> {
            // 按月份数字排序
            Integer month1 = Integer.parseInt(m1.replace("月", ""));
            Integer month2 = Integer.parseInt(m2.replace("月", ""));
            return month1.compareTo(month2);
        });
        date.forEach(n -> {
            String s = n.substring(5,7) + "月";
            month.add(s);
        });
        return month;
    }
}
